import com.im30.jenkins.pipeline.models.ArcDiff
import com.im30.jenkins.pipeline.utils.BuildConfig
import groovy.json.JsonSlurper

def call() {
    properties([
            parameters([
                    string(defaultValue: '', description: '', name: 'DIFF_ID', trim: false),
                    string(defaultValue: '', description: '', name: 'PHID', trim: false)
            ])
    ])

    dockerNode.nodeBuildDocker {
        ArcDiff diff
        BuildConfig buildConfig
        boolean isSuccess = false
        try {
            stage('Preparation') {
                //checkout scm
                try {
                    checkout([
                            $class: 'GitSCM',
                            branches: scm.branches,
                            doGenerateSubmoduleConfigurations: false,
                            extensions: [[
                                                 $class: 'SubmoduleOption',
                                                 disableSubmodules: false,
                                                 parentCredentials: true,
                                                 recursiveSubmodules: true,
                                                 reference: '',
                                                 trackingSubmodules: false
                                         ]],
                            submoduleCfg: [],
                            userRemoteConfigs: scm.userRemoteConfigs
                    ])
                } catch (err) {
                    echo err.getMessage()
                    echo 'Try normal checkout scm'
                    checkout scm
                }

                diff = arcanistUtil.fetchArcDiff(DIFF_ID)
                arcanistUtil.applyPath(DIFF_ID, diff)
            }
            buildConfig = BuildConfig.load(this)
            List<Object> appInfos = buildConfig.getApps()
            projectName = jobUtil.getRepoName()
            echo "diff begin - ${projectName}"
            stage('Report') {
                timeout(10) {
                    for (Object app : appInfos) {
                        echo "Try Sonar: ${app.name}"
                        if (app.sonar == 'Need') {
                            // sh "sonar-scanner -Dsonar.analysis.mode=preview -Dsonar.host.url=http://sonar-tx.http.svc.pre.ali.im30 -Dsonar.sourceEncoding=UTF-8 -Dsonar.login=27023b0400857c5d5ae67f312fcd154006a020ce   -Dsonar.projectKey=FE_${app.name} -Dsonar.sources=.  -Dsonar.exclusions=**/node_modules/**,**/dist/**,**/webapps/**,**/_kfe_buildcache/**| awk 'match(\$0, /Phab-Lint: .*/) {print substr(\$0, RSTART+11, RLENGTH-1)}' | tee -a .phabricator-lint"
                        }

                        echo "Try Lint: ${app.name}"
                        if (app.lint == 'Need') {
                            sh "npm install @im30fe/plugin-lint -D --no-audit --no-optional --only=dev && npm run difflint | awk 'match(\$0, /Phab-Lint: .*/) {print substr(\$0, RSTART+11, RLENGTH-1)}' | tee -a .phabricator-lint"
                        }
                        // sh 'cp text.txt .phabricator-lint'
                    }

                    // if (diff != null && diff.branch == "master") {
                    //     unstable('Build failed!')
                    //     sh 'echo "不应该在 master 分支开发并提交 Diff！\n" >> .phabricator-comment'
                    // }
                    if (currentBuild.result == null || currentBuild.result == 'SUCCESS') {
                        sh 'echo "(NOTE) 编译通过，少年干得不错！" >> .phabricator-comment'
                        isSuccess = true
                    } else {
                        sh 'echo "(WARNING) 少年，这个提交似乎有点问题啊。" >> .phabricator-comment'
                        isSuccess = false
                    }
                }
            }
        } catch (err) {
            unstable('Build failed!')
            echo err.getMessage()
            sh 'echo "(WARNING) 少年，这个提交似乎有点问题啊。" >> .phabricator-comment'
            isSuccess = false
        } finally {
            step([$class: 'PhabricatorNotifier', commentOnSuccess: true,
                  commentWithConsoleLinkOnFailure: true, coverageCheck: true,
                  coverageReportPattern: '**/target/site/jacoco/jacoco*.xml',
                  processLint: true, lintFile: '.phabricator-lint', lintFileSize: '300000', preserveFormatting: true,
                  customComment: true, commentFile: '.phabricator-comment'])

            try {
                if (buildConfig.isAppRepo()) {
                    notifyUtil.notifyNodeDiff(buildConfig.getNotifyConfig(), jobUtil.getRepoName(), diff.revisionID, diff.title.replaceAll("_____im30fe_npm_update______", ""), isSuccess)
                }
            } catch (err) {
                echo err.getMessage()
                echo "${buildConfig}"
                echo "${diff}"
            }

            deleteDir()
        }
    }
}